﻿using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;

namespace GameToolkit
{
    [VolumeComponentMenu("Image Effects/Sketch Line")]
    public class SketchLineEffect : ImageEffectPassData, ImageEffectPropertyBlock
    {
        [SerializeField]
        VolumeParameter<Material> m_Material = new VolumeParameter<Material>();

        [SerializeField]
        VolumeParameter<ImageEffectPass.InjectionPoint> m_RenderEvent = new VolumeParameter<ImageEffectPass.InjectionPoint>() { value = ImageEffectPass.InjectionPoint.BeforeRenderingTransparents};

        [SerializeField]
        ColorParameter m_LineColor = new ColorParameter(Color.black);

        [SerializeField]
        ClampedFloatParameter m_StepOffset = new ClampedFloatParameter(1f, 1f, 4f);

        [SerializeField]
        ClampedFloatParameter m_DepthSharp = new ClampedFloatParameter(1f, 0.1f, 1f);

        int sid_StepOffset;
        int sid_DepthSharp;
        int sid_Color;

        ImageEffectPass.PassData mPdata;

        public override bool IsActive()
        {
            return m_Material.overrideState && m_Material.value != null;
        }

        public override bool IsRenderPassDirty()
        {
            return mPdata.renderPassEvent != m_RenderEvent.value;
        }

        public override void OnActivite(CustomVolumeRenderer volr)
        {
            base.OnActivite(volr);
            sid_StepOffset = Shader.PropertyToID("_Step_Offset");
            sid_DepthSharp = Shader.PropertyToID("_Depth_Sharp");
            sid_Color = Shader.PropertyToID("_Line_Color");
        }

        public override void OnSetupBlitterPassData(ImageEffectPass pass)
        {
            var pdata = new ImageEffectPass.PassData(m_RenderEvent.value, m_Material.value, true);
            pdata.requirements = ScriptableRenderPassInput.Depth | ScriptableRenderPassInput.Normal;
            mPdata = pdata;
            pass.EnqueueBliterPass(pdata, this);
        }

        void ImageEffectPropertyBlock.OnSetupPropertyBlock(MaterialPropertyBlock block)
        {
            block.SetFloat(sid_StepOffset, m_StepOffset.value);
            block.SetFloat(sid_DepthSharp, m_DepthSharp.value);
            block.SetColor(sid_Color, m_LineColor.value);
        }
    }
}
